let BaseController = require('./BaseController')
let fs = require('fs')
let path = require('path')
class 港股通沪历史数据Controller extends BaseController {
    constructor() {
        super();
        this.pageIndex = 1;
        this.pageTotal = '';
        this.baseSrc = `d:/数据指标分类/${new Date().format('yyyyMMdd')}/待入库/07日沪深港通/历史数据/`
        this.file = `港股通(沪)历史数据_${new Date().format('yyyyMMdd')}.csv`
        this.encode = 'UTF-8'
        this.data = [];

    }
    /**
     * 获取url
     */
    getUrl(date) {
        return `http://dcfm.eastmoney.com/EM_MutiSvcExpandInterface/api/js/get?type=HSGTHIS&token=70f12f2f4f091e459a279469fe49eca5&filter=(MarketType=2)&js=var%20OfvlRsWu={%22data%22:(x),%22pages%22:(tp)}&ps=20&p=${this.pageIndex}&sr=-1&st=DetailDate&rt=51100143`
    }

    /**
     * 获取历史数据
     */
    async getHistory() {
        console.log('4港股通(沪)历史数据Controller')
        if (this.pageTotal == '' || this.pageIndex <= this.pageTotal) {
            console.log({ pageIndex: this.pageIndex, pageTota: this.pageTotal })
            let data = await this.getData(this.pageIndex, this.isCache)
            let result = this.axiosDataFormat(data.toString());
            data = result.data
            this.pageTotal = result.pages||0
            this.data = [...this.data, ...data]
            this.pageIndex++;
            await this.getHistory();
        }
    }
    /**
     * 数据格式化
     */
    axiosDataFormat(data) {
        let result = null
        try {
            result = JSON.parse(data.replace(/^var\s\w+?\s*\=/, '').trim())
        } catch (err) {
            try {
                result = eval('(' + data.replace(/^var\s\w+?\s*\=/, '').trim() + ')')
            } catch (err) {
                if (data.indexOf('502 Bad Gateway') > -1) {
                    return []
                } else {
                    console.log(err)
                }

            }
        }
        return result
    }

    /**
     * 写csv
     */
    writeCsv(arr) {
        if (!fs.existsSync(this.baseSrc)) {
            this.mkdirs(this.baseSrc)
        }
        fs.writeFileSync(path.join(this.baseSrc, this.file), this.convertToCSV(arr, 'title'), 'UTF-8')
    }

    async main(startDate = '2015-01-01', isCache = true) {
        this.startDate = startDate;
        this.isCache = isCache;
        console.log('--->4港股通(沪)历史数据Controller')
        await this.getHistory()
        this.writeCsv(this.data);
    }
}

let controller = new 港股通沪历史数据Controller()
module.exports = controller
